load("js/cib_mobile/Barrett.js")
load("js/cib_mobile/BigInt.js")
load("js/cib_mobile/RSA.js")


var   open_time = "";
var urls = {
    USER_AGENT:"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Mobile Safari/537.36",
    ACCEPT:"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
}

var sdf = new SimpleDateFormat("yyyy-MM-dd");


var v6_cib_mobile_debit_java_funcs = {
    checkProxyAvailable: function(){
        return true;
    },
    checkTargetWebsiteAvailable: function(){ return true },
    checkControlAvailable:function () {
        return true;
    },
    login:function(){
        var cardNo = getLoginParams(context)[0];//卡号
        var certNo = getLoginParams(context)[1];//身份证
        var passWord = context.get(Constants.LUA_TASK_TOKEN);

        //请求公钥
        var param = new HashMap();
        param.put("menu", "0100000020");
        var indexHtml = RequestUtil.post("https://3g.cib.com.cn/app/80820.html", param, getHttpPostTwo());
        storeDataToFile(context, indexHtml, "indexHtml.html");
        var first = indexHtml.indexOf("publicKey = ");
        var publicKeyStr = indexHtml.substring(first + "publicKey = ".length, first + "publicKey = ".length + 258);
        publicKeyStr = publicKeyStr.replaceAll("\"", "").replaceAll("\"", "");
        if(publicKeyStr.length() !== 256){
            publicKeyStr = "";
        }
        logger.info("任务【 {} 】公钥【 {} 】",context.get(LUA_TASK_KEY), publicKeyStr);

        //加密密码
        var passWordEncrypt = hsRSAEncrypt(passWord,publicKeyStr);
        logger.info("任务【 {} 】密文【 {} 】",context.get(LUA_TASK_KEY), passWordEncrypt);


        param.clear();
        //登录并返回结果
        var secendUrl = "https://3g.cib.com.cn/app/00002.html";
        param.put("flowsn", "402");
        param.put("hsm_pwd", passWordEncrypt);
        param.put("select_flag", "0");
        param.put("loginname", cardNo);
        param.put("req_zjhm", certNo);
        param.put("pwd", passWordEncrypt);
        var loginResultHtml = RequestUtil.post(secendUrl,param,getHttpPostTwo());
        storeDataToFile(context, loginResultHtml, "loginResult.html");

        var isLoginCorrectFunc = function(loginResultHtml) {
            if(StringUtils.isBlank(loginResultHtml)) {
                return false;
            }
            var doc = Jsoup.parse(loginResultHtml);

            if(equals(doc.select("#cvv2").attr("placeholder"), "卡片签名栏末三位")){
                return false

            }else if(equals("请按以下流程激活信用卡：",doc.select(".words").text())){
                return false
            }
            var checkText = doc.select("h2.mk-title").text()
            logger.info("任务【 {} 】待检查文本: '{}'", context.get(LUA_TASK_KEY), checkText)
            return StringUtils.isNotBlank(checkText) && checkText.contains("尊敬的")
        }

        var getLoginErrorMsgFunc = function(loginResultHtml) {
            if(StringUtils.isBlank(loginResultHtml)) {
                return "登录超时";
            }
            var doc = Jsoup.parse(loginResultHtml);

            var checkText = doc.select("#cvv2").attr("placeholder")
            logger.info("任务【 {} 】待检查文本: '{}'", context.get(LUA_TASK_KEY), checkText)

            var  activateCard = doc.select(".words").text();
            logger.info("任务【 {} 】激活的卡: '{}'", context.get(LUA_TASK_KEY), activateCard)

            if(equals(checkText, "请输入签名栏末三位")){
                return "请输入卡片签名栏末三位"
            }else if(equals("请按以下流程激活信用卡：",activateCard)){
                return "请按以下流程激活信用卡"
            }

            var errorMsg = doc.select("p.result-describe").text();
            logger.info("任务【 {} 】错误信息: {}", context.get(LUA_TASK_KEY), errorMsg)
            return errorMsg
        }

        assertTrueOrThrowException(loginResultHtml, isLoginCorrectFunc, getLoginErrorMsgFunc)
        logger.info("任务【 {} 】登录成功", context.get(LUA_TASK_KEY))
    },
    crawl:function(){
        logger.info("{},借记卡开始",context.get(Constants.LUA_TASK_KEY));

        var cardNum = 1;

        //向上下文中设置信用卡数量
        context.put("debitCardSize",1);

        //构建表头
        createData();

        //获取构建到的表头信息
        var dataList = context.get(ALL_DATA);

        //因为兴业的卡是一张卡，所以只有一个对象
        var creditCardAllData = dataList.get(0);

        //************************ 【获取 余额 并解析】********************************
                    getBalanceHtml()
                    parseBalanceHtml(creditCardAllData)


        //@@@@@@@@@@@@@@@@@@@@@@@@@@【获取开卡时间页面  并解析】@@@@@@@@@@@@@@@@@@@@@@@@
                    getOpenTimeHtml()
                    parseOpenTimeHtml(creditCardAllData)



        //========================【获取卡号、持卡人、开户行页面  并 解析 】==========================
                      getBaseInfoHtml()
                      parseBaseInfoHtml(creditCardAllData)

        //===========================【账单流水】================================

                       //--------------【获取每个月的第一天和最后一天，即使当月没有到月底，返回当前的日期】
                         var monthFirstDay = getMonthFirstDay();
                         var monthLastDay = getMonthLastDay();

                         for(var i = 0; i < 12; i ++){

                             //如果在开卡时间之前  就删除开卡时间之前的月份
                             if(StringUtils.isNotBlank(open_time)){
                                 if (sdf.parse(open_time).after(sdf.parse(monthFirstDay.get(i)))
                                     && sdf.parse(open_time).after(sdf.parse(monthLastDay.get(i)))) {
                                     break;
                                 }
                             }

                             //每月的第一天
                             var firstDay = monthFirstDay.get(i).replaceAll("-", "");
                             //每月的最后一天
                             var lastDay = monthLastDay.get(i).replaceAll("-", "");

                            //初始化billAllData
                            var billAllData =  getDoneBillAllDataHeaderData(creditCardAllData);
                             billAllData.setShoppingSheets(new ArrayList());


                             //【获取 每个月账单的总信息 包括总页数、第一页的消费的总条数 并解析】
                             getBillEveryMonthFirstHtml(cardNum,firstDay,lastDay)
                             parseBillEveryMonthFirstHtml(firstDay)

                             //【每个月账单的总页数】
                            var sumPage =  context.get("totalPages");
                             var sumP = null;
                             if(StringUtils.isNotBlank(sumPage)){
                                  sumP = sumPage.split("/");
                             }
                            logger.info("{},{}月账单的总页数:【{}】",context.get(Constants.LUA_TASK_KEY),firstDay,null == sumP ? "没有消费明细": Integer.parseInt(sumP[1]));

                           //【每个月的账单的总消息的页面 显示的消费信息的条数】
                            var children =  context.get("firstPageExpenseItem");
                            logger.info("{},{}月账单的第一页显示的条数：【{}】",context.get(Constants.LUA_TASK_KEY),firstDay,null == children ? "消费条数是0":children.size()-2);


                             //【获取每个月第一页的 每笔消费信息 并解析】
                                   getEveryMonthEveryExpenseHtml(cardNum,children,firstDay)
                                   parseEveryMonthEveryExpenseHtml(cardNum,children,firstDay,billAllData,creditCardAllData)



                             //【获取每个月账单的 第二页及更多的页数 并解析】
                               if(null != sumP){
                                   //分页
                                   for(var currentPage = 2 ; currentPage <=Integer.parseInt(sumP[1]); currentPage ++) {

                                           getEveryMonthBillMorePageSumItemHtml(cardNum,firstDay,currentPage)
                                           parseEveryMonthBillMorePageSumItemHtml(cardNum,firstDay,currentPage)

                                             var  childs =  context.get("morePageSumItem");
                                              logger.info("{},{}月{}页，总【{}】条数",context.get(Constants.LUA_TASK_KEY),firstDay,currentPage,null == childs ? "没有消费明细":childs.size()-2);

                                              getEveryMonthBillMorePageExpenseHtml(cardNum,firstDay,currentPage,childs)
                                              parseEveryMonthBillMorePageExpenseHtml(firstDay,currentPage,childs,billAllData,creditCardAllData)
                                   }
                               }

                                 //处理账单
                                 handlerEveryMonth(monthFirstDay.get(i),billAllData)
                         }


                  //()()()()()()()()()()()【定期 活期】()()()()()()()()()()()
                          getDepositHtml()
                          parseDepositHtml(creditCardAllData)


    },
    exitLogin :function () {}
}


/**
 * 给pwd加密
 * @type {string}
 */
function hsRSAEncrypt(str,publicKey){
    if(publicKey=="") return str;
    setMaxDigits(130);
    var key = new RSAKeyPair("10001" , "" , publicKey);
    var enStr = encryptedString(key,str);
    return enStr;
}


/**
 * 【获取卡号、开户行、持卡人页面】
 */
function  getBaseInfoHtml(){
    logger.info("{},开始获取借记卡【卡号、开户行、持卡人】页面",context.get(Constants.LUA_TASK_KEY));

    var openBankURL = "https://3g.cib.com.cn/app/20901.html" ;

    var param = new HashMap();
        param.put("flowsn", "0");
        param.put("listcardno", "0");
        param.put("listno", "0");

    var openBankHtml =RequestUtil.post(openBankURL,param,getHttpPostTwo());
        storeDataToFile(context,openBankHtml,   "openBankXml.html");

     context.put("openBankHtml",openBankHtml);
    if(openBankHtml.contains("该业务仅支持借记卡办理，请使用借记卡登录后继续办理。")){
        throw  new BankException(BALO_99604_15, errorMsgMap.get(BALO_99604_15));
    }

}


/**
 * 【解析卡号、开户行、持卡人页面】
 */
function  parseBaseInfoHtml(creditCardAllData){
        logger.info("{},开始解析借记卡【卡号、开户行、持卡人】页面",context.get(Constants.LUA_TASK_KEY));

         var  openBankHtml = context.get("openBankHtml");
         try{
             if(StringUtils.isNotBlank(openBankHtml)){
                 var openBankDoc = Jsoup.parse(openBankHtml);

                 var openBank = openBankDoc.select("body > div.content > div.purchase-info > ul > li.top-inline.clearfix > span").text().trim().replaceAll("\\u00A0", "");
                 var fullcardNum = openBankDoc.select("body > div.content > form > div.card-info.card_bg > div.card-account > em:nth-child(2)").text().trim().replaceAll("\\s*", "").replaceAll("\\u00A0", "");
                 var name = openBankDoc.select("body > div.content > form > div.card-info.card_bg > div:nth-child(2) > span.fl.mat5").text().trim().replaceAll("\\u00A0", "");;

                 //完整卡号
                 creditCardAllData.setFullCardNum(fullcardNum);
                 //卡号后四位
                 creditCardAllData.setCardNum(fullcardNum.substring((fullcardNum.length()-4), (fullcardNum.length())));
                 //开户行
                 creditCardAllData.setOpenBank(openBank);
                 //持卡人
                 creditCardAllData.setNameOnCard(name);
             }
         }catch (e) {
             logger.info("{},解析借记卡基本信息页面异常：{}",context.get(Constants.LUA_TASK_KEY),e);
             statCaughtExceptionByJS(context, e);
         }
}


/**
 * 【获取余额页面】
 */
function getBalanceHtml(){
    logger.info("{},开始获取兴业借记卡【余额】页面",context.get(Constants.LUA_TASK_KEY));

    //var huoTwoUrl = "https://3g.cib.com.cn/app/10020.html";
   var huoTwoUrl =  "https://3g.cib.com.cn/app/80820.html";
        var param = new HashMap();
           /* param.put("flowsn", "201");
            param.put("listcardno", "0");
            param.put("listno", "0");
            param.put("secmenu", "0200000302");
            param.put("menu", "0100000020");
            param.put("isJump", "1");*/
           param.put("menu","0100000020");

    // var yueHtml = RequestUtil.post(huoTwoUrl,param,getHttpPostOne());
    var yueHtml = RequestUtil.post(huoTwoUrl,param,getHttpPostTwo());
    storeDataToFile(context,yueHtml,  "card_yue.html");

    context.put("yueHtml",yueHtml);
}


/**
 * 【解析余额页面】
 */
function parseBalanceHtml(creditCardAllData){
    logger.info("{},开始解析兴业借记卡【余额】页面",context.get(Constants.LUA_TASK_KEY));

   var yueHtml =  context.get("yueHtml");
   try {
       if(StringUtils.isNotBlank(yueHtml)){

           var yueDoc = Jsoup.parse(yueHtml);
            var balance = yueDoc.select("body > div.content > form > div > div > div:nth-child(3) > strong > em").text().trim().replaceAll(",","");


           creditCardAllData.setBalance(new BigDecimal(balance));
       }

   }catch (e) {
       logger.info("{},解析兴业借记卡【余额】页面异常：{}",context.get(Constants.LUA_TASK_KEY),e);
       statCaughtExceptionByJS(context, e);
   }

}


/**
 * 【获取开卡时间页面】
 */
function getOpenTimeHtml(){
    logger.info("{},开始获取兴业借记卡【开卡时间】页面",context.get(Constants.LUA_TASK_KEY));

      var openTimeBeforeURL = "https://3g.cib.com.cn/app/10020.html";
       var param = new HashMap();
            param.put("flowsn", "201");
            param.put("listcardno", "0");
            param.put("listno", "0");
            param.put("secmenu", "0200000302");
            param.put("menu", "0100000020");
            param.put("isJump", "1");
    RequestUtil.post(openTimeBeforeURL,param,getHttpPostOne());

    var huoqiURL = "https://3g.cib.com.cn/app/10020.html";
        param.clear();
        param.put("flowsn", "250");
        param.put("mxlistno", "001");
        param.put("cardindex", "0");
    var openTimeHtml =RequestUtil.post(huoqiURL,param,getHttpPostThree());
    storeDataToFile(context,openTimeHtml,   "card_openTime.html");

    context.put("openTimeHtml",openTimeHtml);

}


/**
 * 【解析 开卡时间页面】
 */
function parseOpenTimeHtml(creditCardAllData){
    logger.info("{},开始解析兴业借记卡【开卡时间】页面",context.get(Constants.LUA_TASK_KEY));

    var openTimeHtml = context.get("openTimeHtml");
    try {
         if(StringUtils.isNotBlank(openTimeHtml)){
             var openTimeDoc = Jsoup.parse(openTimeHtml);
             //开户时间
             open_time = openTimeDoc.select("body > div.content > div.product-introduce > div:nth-child(4) > div:nth-child(1) > span").text().trim().replaceAll("/", "-");
             // 开户时间
             creditCardAllData.setOpenTime(yyyy_MM_dd_PARSER.parse(open_time));
         }

    }catch (e) {
        logger.info("{},开始解析兴业借记卡【开卡时间】页面异常：{}",context.get(Constants.LUA_TASK_KEY),e);
        statCaughtExceptionByJS(context, e);
    }
}


/**
 * 【获取每个月账单的总信息 包括总页数、第一页的消费的总条数】
 */
function getBillEveryMonthFirstHtml(cardNum,firstDay,lastDay){
    logger.info("{},获取借记卡【{}】月账单的总信息",context.get(Constants.LUA_TASK_KEY),firstDay);


    var baseURL="https://3g.cib.com.cn/app/80820.html";
    var param = new HashMap();
    param.put("flowsn", "50");
    param.put("secmenu", "0200000300");
    RequestUtil.post(baseURL,param,getHttpPostOne());

    var billsDetailTwoURL = "https://3g.cib.com.cn/app/10040.html";
    param.clear();
    param.put("flowsn", "4");
    param.put("listcardno", "0");
    param.put("listno", "0");
    RequestUtil.post(billsDetailTwoURL,param,getHttpPostFour());

    param.clear();
    param.put("flowsn", "15");
    param.put("xxh", "001");
    param.put("begindate", firstDay);
    param.put("enddate",lastDay);
    param.put("qrytype", "1");
    var billEveryMonthTotalMsgHtml = RequestUtil.post(billsDetailTwoURL,param,getHttpPostFour());

    storeDataToFile(context,billEveryMonthTotalMsgHtml, cardNum + "_bill_" + firstDay + "totalMsg.html");
    /**
     * 判断有没有
     */
    if(billEveryMonthTotalMsgHtml.contains("对不起，找不到符合条件的交易明细。")){
        return;
    }

    context.put("billEveryMonthTotalMsgHtml",billEveryMonthTotalMsgHtml);
}


/**
 * 【解析每个月账单的总信息(账单的第一页) 包括总页数、第一页的消费的总条数 】
 */
function parseBillEveryMonthFirstHtml(firstDay) {
    logger.info("{},解析借记卡【{}】月账单的总信息、包括【总页数、第一页的消费的总条数】",context.get(Constants.LUA_TASK_KEY),firstDay);

     var  billEveryMonthTotalMsgHtml = context.get("billEveryMonthTotalMsgHtml");
    try{
        if(StringUtils.isNotBlank(billEveryMonthTotalMsgHtml)) {

            var billEveryMonthFirstPageDoc = Jsoup.parse(billEveryMonthTotalMsgHtml);

            var sumPage = billEveryMonthFirstPageDoc.select("body > div.content > div.mat10 > form:nth-child(3) > p > span > em").text().replaceAll("\\[", "").replaceAll("\\]", "");

            var billsDetailThreeForm = billEveryMonthFirstPageDoc.select("body > div.content > div.mat10 > form:nth-child(1)");
            var children = billsDetailThreeForm.get(0).children();
            context.put("totalPages",sumPage);
            context.put("firstPageExpenseItem",children);

        }

    }catch (e) {
        logger.info("{},解析借记卡【{}】月账单的总信息、包括【总页数、第一页的消费的总条数】的异常：{}",context.get(Constants.LUA_TASK_KEY),firstDay,e);
        statCaughtExceptionByJS(context, e);
    }
}


/**
 * 【获取每个月账单的第一页的每笔消费信息】
 */
function getEveryMonthEveryExpenseHtml(cardNum,children,firstDay){
    logger.info("{},获取借记卡【{}】月账单的总信息（第一页）的每笔消费信息",context.get(Constants.LUA_TASK_KEY),firstDay);
    var billsDetailTwoURL = "https://3g.cib.com.cn/app/10040.html";

    if(null != children){
        for(var i = 2 ; i < children.size();i++) {

            var param = new HashMap();
                param.put("flowsn", "200");
                param.put("listno", (i - 2) + "");
            var billsDetailFour = RequestUtil.post(billsDetailTwoURL, param, getHttpPostOne());
            storeDataToFile(context, billsDetailFour, cardNum + "_bill_firstPage_shopping_sheets_" +firstDay+"月"+ (i - 1) + "Item.html");

            context.put(i,billsDetailFour);
        }
    }
}


/**
 * 【解析每个月账单的第一页的每笔消费信息】
 */
function parseEveryMonthEveryExpenseHtml(cardNum,children,firstDay,billAllData,creditCardAllData){
    logger.info("{},解析借记卡【{}】月账单的总信息【第一页】的每笔消费信息",context.get(Constants.LUA_TASK_KEY),firstDay);

    var order = 0;

      try{
          if(null != children ) {
              for (var i = 2; i < children.size(); i++) {
                  var expense = new Expense();
                  var everyMonthFirstPageExpenseItem = context.get(i);


                  if (StringUtils.isNotBlank(everyMonthFirstPageExpenseItem)) {

                      var billEveryMonthFirstPageExpenseDoc = Jsoup.parse(everyMonthFirstPageExpenseItem);

                      //记账时间
                      var post_date = billEveryMonthFirstPageExpenseDoc.select("body > div.content > div.product-introduce > div:nth-child(3) > div:nth-child(2) > span").text().trim().replaceAll("/", "-");

                      //交易时间
                      var trans_date = billEveryMonthFirstPageExpenseDoc.select("body > div.content > div.product-introduce > div:nth-child(3) > div:nth-child(1) > span").text().trim().replaceAll("/", "-");

                      //交易金额
                      var amount_moneyText = billEveryMonthFirstPageExpenseDoc.select("body > div.content > div.product-introduce > div:nth-child(1) > div > p").text().trim();
                      var amount_money = billEveryMonthFirstPageExpenseDoc.select("body > div.content > div.product-introduce > div:nth-child(1) > div > span").text().trim().replaceAll(",", "");


                      //账户余额
                      var balance = billEveryMonthFirstPageExpenseDoc.select("body > div.content > div.product-introduce > div:nth-child(2) > div:nth-child(2) > span").text().trim().replaceAll(",", "");

                      //对方信息   包括对方持卡人 和对方卡号      (步延伟5218991349688785)
                      var name_on_opposite_card = billEveryMonthFirstPageExpenseDoc.select("body > div.content > div.product-introduce > div:nth-child(4) > div > span").text().trim();
                      var p = Pattern.compile("([\u4e00-\u9fa5]+)");
                      var m = p.matcher(name_on_opposite_card);
                      var sb = new StringBuffer("");
                      while (m.find()) {
                          sb.append(URLDecoder.decode(m.group(1), "UTF-8"));
                      }

                      //对方卡号
                      var opposite_card_no = billEveryMonthFirstPageExpenseDoc.select("body > div.content > div.product-introduce > div:nth-child(4) > div > span > span").text().trim();

                      //对方银行
                      var opposite_bank = billEveryMonthFirstPageExpenseDoc.select("body > div.content > div.product-introduce > div:nth-child(5) > div > span").text().trim();

                      //交易摘要
                      var description = billEveryMonthFirstPageExpenseDoc.select("body > div.content > div.product-introduce > div:nth-child(2) > div:nth-child(1) > span").text().trim();
                      if (amount_moneyText.contains("收入")) {
                          amount_money = "-" + amount_money;
                      } else if (amount_moneyText.contains("支出")) {
                          amount_money = "+" + amount_money;
                      }
                      //备注
                      var remark = billEveryMonthFirstPageExpenseDoc.select(" body > div.content > div.product-introduce > div:nth-child(6) > div > span").text().trim();

                      // 消费id
                      expense.setId(UUID.randomUUID().toString());
                      // 卡号末四位
                      expense.setCardNum(creditCardAllData.getCardNum());
                      // 记账日期
                      expense.setPostDate(yyyy_MM_dd_PARSER.parse(post_date));

                      // 排序
                      expense.setOrderIndex(++order);
                      // 交易时间
                      expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(trans_date));
                      // 币种
                      expense.setCurrencyType("CNY");
                      // 消费金额
                      expense.setAmountMoney(new BigDecimal(amount_money));
                      expense.setCategory(classify(description,expense.getAmountMoney()));
                      // 余额
                      expense.setBalance(new BigDecimal(balance));
                      // 交易地点
                      expense.setTransAddr("");
                      // 交易方式
                      expense.setTransMethod("");
                      // 交易通道
                      expense.setTransChannel("");
                      // 描述
                      expense.setDescription(description);
                      // 备注
                      expense.setRemark(remark);
                      // 对方卡号
                      expense.setOppositeCardNo(opposite_card_no);
                      // 对方银行
                      expense.setOppositeBank(opposite_bank);
                      // 对方户名
                      expense.setNameOnOppositeCard(sb.toString());

                      billAllData.getShoppingSheets().add(expense);

                  }
                  //将每笔消费的序号添加到上下文中，方便第二页用
                  context.put("order", order)
              }
          }
      }catch (e) {
          logger.info("{},解析借记卡【{}】月账单的总信息【第一页】的每笔消费信息异常：{}",context.get(Constants.LUA_TASK_KEY),firstDay,e);
          statCaughtExceptionByJS(context, e);
      }







}


/**
 * 【获取每个月账单 第二页 及更多的页 的 当页 的总条数】
 */
function getEveryMonthBillMorePageSumItemHtml(cardNum,firstDay,currentPage) {
    logger.info("{},获取借记卡【{}】月账单的第【{}】页的消费总条数",context.get(Constants.LUA_TASK_KEY),firstDay,currentPage);
    var billsDetailTwoURL = "https://3g.cib.com.cn/app/10040.html";

      var param = new HashMap();
         param.put("beginNo",  (currentPage - 1) + "1");
         param.put("flowsn", "75");
    var billsDetailsNextPageHtml = RequestUtil.post(billsDetailTwoURL,param,getHttpPostFour());
    storeDataToFile(context,billsDetailsNextPageHtml, cardNum + "_bill_shopping_sheets_"+ firstDay+"月"+currentPage+ "Page.html");

    context.put("billsDetailsNextPageHtml",billsDetailsNextPageHtml);
}


/**
 * 【解析每个月账单 第二页 及更多的页 的消费 总数】
 */
function parseEveryMonthBillMorePageSumItemHtml(cardNum,firstDay,currentPage) {
    logger.info("{},解析借记卡【{}】月账单的第【{}】页的消费总条数",context.get(Constants.LUA_TASK_KEY),firstDay,currentPage);


    try{
      var  billsDetailsNextPageHtml =  context.get("billsDetailsNextPageHtml");
      if(StringUtils.isNotBlank(billsDetailsNextPageHtml)){

          var billsDetailsNextPageDoc = Jsoup.parse(billsDetailsNextPageHtml);
          var billsDetailsNextPage = billsDetailsNextPageDoc.select("body > div.content > div.mat10 > form:nth-child(1)");
          var childs = billsDetailsNextPage.get(0).children();

          context.put("morePageSumItem",childs);
      }
    }catch (e) {
        logger.info("{},解析借记卡【{}】月账单的第【{}】页的消费总条数 异常：{}",context.get(Constants.LUA_TASK_KEY),firstDay,currentPage,e);
        statCaughtExceptionByJS(context, e);
    }
}


/**
 * 【每个月账单的 第二页及更多的页数   每页上的每笔消费】
 */
function getEveryMonthBillMorePageExpenseHtml(cardNum,firstDay,currentPage,childs){
    logger.info("{},获取借记卡【{}】月账单的【{}】页的每笔消费详情的页面",context.get(Constants.LUA_TASK_KEY),firstDay,currentPage);

    if(null != childs) {
        var billsDetailTwoURL = "https://3g.cib.com.cn/app/10040.html";
        for (var i = 2; i < childs.size(); i++) {

            var param = new HashMap();
                param.put("flowsn", "200");
                param.put("listno", (currentPage - 1) + "" + (i - 2));
            var billsDetailFour = RequestUtil.post(billsDetailTwoURL, param, getHttpPostOne());
            storeDataToFile(context, billsDetailFour, cardNum + "_bill_shopping_sheets_" +firstDay+"月"+currentPage+"Page"+((currentPage - 1) + "" + (i - 1)) + ".html");

            context.put(i,billsDetailFour);
        }
    }
}


/**
 * 【解析每个月账单的  第二页及更多的页数  每页上的每笔消费】
 */
function  parseEveryMonthBillMorePageExpenseHtml(firstDay,currentPage,childs,billAllData,creditCardAllData){
    logger.info("{},解析借记卡【{}】月账单的第【{}】页的每笔消费详情的页面",context.get(Constants.LUA_TASK_KEY),firstDay,currentPage);

    var order = 10;
    try{
        if(null != childs) {

            for (var i = 2; i < childs.size(); i++) {
                var expense = new Expense();

                var billsDetailFour = context.get(i);

                if (StringUtils.isNotBlank(billsDetailFour)) {


                    var billsDetailFourDoc = Jsoup.parse(billsDetailFour);
                    //记账时间
                    var post_date = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(3) > div:nth-child(2) > span").text().trim().replaceAll("/", "-");
                    //交易时间
                    var trans_date = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(3) > div:nth-child(1) > span").text().trim().replaceAll("/", "-");

                    //交易摘要
                    var description = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(2) > div:nth-child(1) > span").text().trim();

                    //交易金额
                    var amount_moneyText = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(1) > div > p").text().trim();
                    var amount_money = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(1) > div > span").text().trim().replaceAll(",", "");
                    if (amount_moneyText.contains("收入")) {
                        amount_money = "-" + amount_money;
                    } else if (amount_moneyText.contains("支出")) {
                        amount_money = "+" + amount_money;
                    }

                    //账户余额
                    var balance = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(2) > div:nth-child(2) > span").text().trim().replaceAll(",", "");
                    //对方信息   包括对方持卡人 和对方卡号      (步延伟5218991349688785)
                    var name_on_opposite_card = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(4) > div > span").text().trim();
                    var p = Pattern.compile("([\u4e00-\u9fa5]+)");
                    var m = p.matcher(name_on_opposite_card);
                    var sb = new StringBuffer("");
                    var str = "";
                    while (m.find()) {
                        sb.append(URLDecoder.decode(m.group(1), "UTF-8"));
//		        	str+=m.group(1);
                    }

                    //对方卡号
                    var opposite_card_no = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(4) > div > span > span").text().trim();

                    //对方银行
                    var opposite_bank = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(5) > div > span").text().trim();

                    //备注
                    var remark = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(6) > div > span").text().trim();

                    // 消费id
                    expense.setId(UUID.randomUUID().toString());
                    // 卡号末四位
                    expense.setCardNum(creditCardAllData.getCardNum());
                    // 记账日期
                    expense.setPostDate(yyyy_MM_dd_PARSER.parse(post_date));
                    // 排序
                    expense.setOrderIndex(++order);
                    // 交易时间
                    expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(trans_date));
                    // 币种
                    expense.setCurrencyType("CNY");
                    // 消费金额
                    expense.setAmountMoney(new BigDecimal(amount_money));
                    expense.setCategory(classify(description,expense.getAmountMoney()));
                    // 余额
                    expense.setBalance(new BigDecimal(balance));
                    // 交易地点
                    expense.setTransAddr("");
                    // 交易方式
                    expense.setTransMethod("");
                    // 交易通道
                    expense.setTransChannel("");
                    // 描述
                    expense.setDescription(description);
                    // 备注
                    expense.setRemark(remark);
                    // 对方卡号
                    expense.setOppositeCardNo(opposite_card_no);
                    // 对方银行
                    expense.setOppositeBank(opposite_bank);
                    // 对方户名
                    expense.setNameOnOppositeCard(sb.toString());

                    billAllData.getShoppingSheets().add(expense);


                }
            }
        }
    }catch (e) {
        logger.info("{},解析借记卡【{}】月账单的【{}】页的每笔消费详情的页面异常：{}",context.get(Constants.LUA_TASK_KEY),firstDay,currentPage,e);
        statCaughtExceptionByJS(context, e);
    }
}


/**
 * 【处理每个月账单的表头】
 */
function handlerEveryMonth(firstDay,billAllData){
    logger.info("{},处理【{}】月表头",context.get(Constants.LUA_TASK_KEY),firstDay);

    billAllData.setBillMonth(firstDay.substring(0, 7));//格式:yyyy-MM   2017-06
    billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(firstDay));
    billAllData.setNewBalance(null);
    billAllData.setUsdNewBalance(null);
    billAllData.setMinPayment(null);
    billAllData.setUsdMinPayment(null);
    billAllData.setLastBalance(null);
    billAllData.setUsdLastBalance(null);
    billAllData.setLastPayment(null);
    billAllData.setUsdLastPayment(null);
    billAllData.setNewCharges(null);
    billAllData.setUsdNewCharges(null);
    billAllData.setInterest(null);
    billAllData.setUsdInterest(null);
    billAllData.setUsdInterest(null);
    billAllData.setCreditLimit(null);
    billAllData.setUsdCreditLimit(null);
    billAllData.setCashLimit(null);
    billAllData.setUsdCashLimit(null);



}


/**
 * 【获取定期的页面】
 */
function getDepositHtml(){
    logger.info("{}，获取定期活期的页面",context.get(Constants.LUA_TASK_KEY));

    /**
     * 活期
     */
    var huoOne = "https://3g.cib.com.cn/app/80820.html";
    var param = new HashMap();
        param.put("menu", "0100000020");
        param.put("divtype", "");
    RequestUtil.post(huoOne,param,getHttpPostOne());

    var huoTwo = "https://3g.cib.com.cn/app/10020.html";
        param.clear();
        param.put("flowsn", "201");
        param.put("listcardno", "0");
        param.put("listno", "0");
    var huoTwoHtml = RequestUtil.post(huoTwo,param,getHttpPostOne());
    storeDataToFile(context,huoTwoHtml, "card_cunchu.html");

    context.put("deposits",huoTwoHtml);

}

/**
 * 【解析定期的页面】
 */
function parseDepositHtml(creditCardAllData){
    logger.info("{}，解析定期活期的页面",context.get(Constants.LUA_TASK_KEY));

    try{
      var  huoTwoHtml=  context.get("deposits");

        var huoTwoDoc = Jsoup.parse(huoTwoHtml);
        var tables = huoTwoDoc.select("table");
        var list = new ArrayList();
        for(var i = 0;i < tables.size()-1; i++) {
           var  deposit = new CreditCardTimeDeposit();
            var text = huoTwoDoc.select("body > div.content > form > table:nth-child("+(4+i)+") > tbody > tr:nth-child(1) > td:nth-child(1)").text().trim();
            if(equals(text,"人民币活期存款")){
                // 定期金额
                deposit.setBalance(creditCardAllData.getBalance());
                // 定期类型
                deposit.setDepositType("活期储蓄存款");
                // 定期币种
                deposit.setCurrencyType("CNY");
                // 存期
                deposit.setPeriod(null);
                // 存期单位
                deposit.setPeriodUnit("");
                list.add(deposit)
            }
            creditCardAllData.setDeposits(list)
        }

    }catch (e) {
        logger.info("{}，解析定期活期的页面异常：{}",context.get(Constants.LUA_TASK_KEY),e);
        statCaughtExceptionByJS(context, e);
    }


}

/**
 * 获取6个月的第一天  格式:2017-01-01
 * @return
 * @throws Exception
 */

function  getMonthFirstDay(){
    var lst = new ArrayList();

    var calendar = new GregorianCalendar();
    var dfdate = new SimpleDateFormat("yyyy-MM-dd");

    for (var i = 0; i < 12; i++) {

        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, -1 * i);

        var gcLast = Calendar.getInstance();
        gcLast.setTime(calendar.getTime());
        gcLast.set(Calendar.DAY_OF_MONTH, 1);
        lst.add(dfdate.format(gcLast.getTime()));
    }
    return lst;
}

/**
 * 获取六个月的最后一天,当月就返回到今天
 */
function getMonthLastDay(){
    var lst = new ArrayList();

    var calendar = new GregorianCalendar();

    var dfdate = new SimpleDateFormat("yyyy-MM-dd");

    for (var i = -1; i < 11; i++) {

        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, -1 * i);

        var gcLast =  Calendar.getInstance();
        gcLast.setTime(calendar.getTime());
        gcLast.set(Calendar.DATE, 1);
        gcLast.add(Calendar.DATE, -1);
        if (gcLast.getTime().after(new Date())) {
            lst.add(dfdate.format(new Date()));
        } else {
            lst.add(dfdate.format(gcLast.getTime()));
        }
    }
    return lst;
}



/*
 * 返回Referer值带有80820的httpost
 * @param
 * @return
 */
function  getHttpPostOne(){
    var header = new HashMap();
    header.put("Referer", "https://3g.cib.com.cn/app/80820.html");
    header.put("User-Agent", urls.USER_AGENT);
    header.put("Origin", "https://3g.cib.com.cn");
    header.put("Host", "3g.cib.com.cn");
    header.put("Accept", urls.ACCEPT);
    return header;
}

/**
 * 返回referer带有00002的httppost
 * @param
 * @return
 */
function   getHttpPostTwo(){
    var header = new HashMap();
    header.put("Referer", "https://3g.cib.com.cn/app/00002.html");
    header.put("User-Agent", urls.USER_AGENT);
    header.put("Origin", "https://3g.cib.com.cn");
    header.put("Host", "3g.cib.com.cn");
    header.put("Accept", urls.ACCEPT);
    return header;
}

/**
 * 返回referer带有10020的httppost
 * @param
 * @return
 */
function   getHttpPostThree(){

    var header = new HashMap();
    header.put("Referer", "https://3g.cib.com.cn/app/10020.html");
    header.put("User-Agent", urls.USER_AGENT);
    header.put("Origin", "https://3g.cib.com.cn");
    header.put("Host", "3g.cib.com.cn");
    header.put("Accept", urls.ACCEPT);
    return header;
}

/**
 * 返回referer带有10040的httppost
 * @param
 * @return
 */
function   getHttpPostFour(){

    var  header = new HashMap();
    header.put("Referer", "https://3g.cib.com.cn/app/10040.html");
    header.put("User-Agent", urls.USER_AGENT);
    header.put("Origin", "https://3g.cib.com.cn");
    header.put("Host", "3g.cib.com.cn");
    header.put("Accept", urls.ACCEPT);
    return header;
}